package com.share.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.dmain.vo.FeeRuleRequest;
import com.share.dmain.vo.FeeRuleResponse;
import com.share.rule.domain.FeeRule;
import com.share.rule.domain.FeeRuleRequestForm;
import com.share.rule.domain.FeeRuleResponseVo;
import com.share.service.FeeRuleService;
import com.share.mapper.FeeRuleMapper;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author 肆
 * @description 针对表【fee_rule(费用规则表)】的数据库操作Service实现
 * @createDate 2025-03-27 11:13:30
 */
@Service
public class FeeRuleServiceImpl extends ServiceImpl<FeeRuleMapper, FeeRule> implements FeeRuleService {

    @Autowired
    private FeeRuleMapper feeRuleMapper;

    @Autowired
    private KieContainer kieContainer;
    /**
     * 分页查询费用规则列表
     *
     * @param feeRule
     * @return
     */
    @Override
    public List<FeeRule> selectFeeRuleList(FeeRule feeRule) {
        return feeRuleMapper.selectFeeRuleList(feeRule);
    }

    /**
     * 获取所有费用规则列表
     */
    @Override
    public List<FeeRule> getALLFeeRuleList() {
        return feeRuleMapper.selectList(new LambdaQueryWrapper<FeeRule>().eq(FeeRule::getStatus, "1"));
    }


    /**
     * 计算订单费用
     * @param feeRuleRequestForm
     * @return
     */
    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm feeRuleRequestForm) {
        //1 开启会话
        KieSession kieSession = kieContainer.newKieSession();

        //2 创建传入数据对象 设置数据
        FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
        feeRuleRequest.setDurations(feeRuleRequestForm.getDuration());

        //3 创建返回数据对象
        FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
        kieSession.setGlobal("feeRuleResponse", feeRuleResponse);

        //4 对象传入到会话对象里面
        kieSession.insert(feeRuleRequest);

        //5 触发规则
        kieSession.fireAllRules();

        //6 中止会话
        kieSession.dispose();

        //7 封装返回需要数据
        FeeRuleResponseVo feeRuleResponseVo = new FeeRuleResponseVo();
        feeRuleResponseVo.setTotalAmount(new BigDecimal(feeRuleResponse.getTotalAmount()));
        feeRuleResponseVo.setFreePrice(new BigDecimal(feeRuleResponse.getFreePrice()));
        feeRuleResponseVo.setFreeDescription(feeRuleResponse.getFreeDescription());
        feeRuleResponseVo.setExceedPrice(new BigDecimal(feeRuleResponse.getExceedPrice()));
        feeRuleResponseVo.setExceedDescription(feeRuleResponse.getExceedDescription());

        return feeRuleResponseVo;
    }
}




